<script setup>
import SearchTable from "./component/SearchOutline.vue"
import VennChart from "./component/Venn.vue"
import VennCharts from "./component/newVenn.vue"
import moment from "moment";
import {getTodayCurve, getAlarmLevelRankList, getAlarmUnitRank, getAmbulanceAlarmRank, getAmbulanceVennList, getAlertable, getCurve, getDictDetail } from "./utils"

import * as echarts from 'echarts';
import { CirclePlus, VideoPlay } from '@element-plus/icons-vue'
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue"

import { globalStore } from "@/store/global";
const globalVue = globalStore();

const instance = getCurrentInstance()
const _this = instance.appContext.config.globalProperties //vue3获取当前this

// 生命周期
onMounted(() => {
  init();
  getSelect();
})

let getSelect = async () => {
  selectClassification.value = await globalVue.getSelect('classificationSelect');
  let algorithm_type = await getDictDetail(instance, {name: 'camera_algorithm'});
  console.log(algorithm_type,'8193178927389107238901738163476197864378');
  selectAlgorithm.value = algorithm_type?.data

  let list = await getDictDetail(instance, {name: 'alarm_algorithm'});
  list.data.unshift({
    label: "All",
    value: ''
  })
  algorithmSelect.value = list.data;
  instance.proxy.$http.get('archiveData.getCitySelect').then(res=>{
    selectCity.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
}
const algorithmSelect = ref([]);
const selectCity = ref([]);
const selectAlgorithm = ref([]);
const selectClassification = ref([]);

let type_color = [
  {type: 1, label: 'Phone', color: 'rgb(250, 56, 59)'},
  {type: 2, label: 'Smoking Smoke', color: 'rgb(248, 122, 13)'},
  {type: 3, label: 'Wheelchair seating', color: 'rgb(224, 171, 36)'},
  {type: 4, label: 'Occlusion', color: 'rgb(183, 110, 222)'},
]


// Today’s alarm analysis
const today = ref(null);
let todayFirst = true;
const todayLoading = ref(true);

// Comparative analysis of alarms
const analysis = ref(null);
let analysisFirst = true;
const analysisLoading = ref(true);

// Vehicle Alarm Ranking
const dimensions = ref(null);
let dimensionsFirst = true;
const dimensionsLoading = ref(true);

// Alarm level proportion
const proportion = ref(null);
let proportionFirst = true;
const proportionLoading = ref(true);
const alarmLevelRankLists = reactive({
  list: []
});

// Ranking of alarms for stationed units
const rankList = reactive([
  { label: 'Chinese Medical Center', value: 0, imgSrc: require('@/assets/image/alarm/ico_top1@2x.png') },
  { label: 'Chinese Medical Center', value: 0, imgSrc:  require('@/assets/image/alarm/ico_top2@2x.png') },
  { label: 'Chinese Medical Center', value: 0, imgSrc: require('@/assets/image/alarm/ico_top3@2x.png') },
  { label: 'Chinese Medical Center', value: 0, imgSrc: require('@/assets/image/alarm/ico_top4@2x.png') },
  { label: 'Chinese Medical Center', value: 0, imgSrc: require('@/assets/image/alarm/ico_top5@2x.png') },
])

const searchForm = reactive({
  date: [moment().subtract(1, 'months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
  ambulanceId: '',
  alarmType: ''
})

const Venn = reactive({
  phone: {
    type: ['phone'],
    value: 0
  },
  smoke: {
    type: ['smoke'],
    value: 0
  },
  wheelchair: {
    type: ['wheelchair'],
    value: 0
  },
  occlusion: {
    type: ['occlusion'],
    value: 0
  },
  
  phone_smoke: {
    type: ['phone', 'smoke'],
    value: 0
  },
  phone_wheelchair: {
    type: ['phone', 'wheelchair'],
    value: 0
  },
  phone_occlusion: {
    type: ['phone', 'occlusion'],
    value: 0
  },
  smoke_wheelchair: {
    type: ['smoke', 'wheelchair'],
    value: 0
  },
  smoke_occlusion: {
    type: ['smoke', 'occlusion'],
    value: 0
  },
  wheelchair_occlusion: {
    type: ['wheelchair', 'occlusion'],
    value: 0
  },

  phone_smoke_wheelchair: {
    type: ['phone', 'smoke', 'wheelchair'],
    value: 0
  },
  phone_smoke_occlusion: {
    type: ['phone', 'smoke', 'occlusion'],
    value: 0
  },
  smoke_wheelchair_occlusion: {
    type: ['smoke', 'wheelchair', 'occlusion'],
    value: 0
  },
  phone_wheelchair_occlusion: {
    type: ['phone', 'wheelchair', 'occlusion'],
    value: 0
  },

  phone_smoke_wheelchair_occlusion: {
    type: ['phone', 'smoke', 'wheelchair', 'occlusion'],
    value: 0
  },
})

function onSearch(){
  init();
}

async function init(){
  let time = new Date()
  let paramsTodayCurve = {
    type: searchForm.type,
    ambulanceId: searchForm.ambulanceId,
    startTime: moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  let params = {
    type: searchForm.type,
    ambulanceId: searchForm.ambulanceId,
    alarmType: searchForm.alarmType,
    startTime: searchForm.date && searchForm.date[0] + ' 00:00:00' || moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: searchForm.date && searchForm.date[1] + ' 23:59:59' || moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  let LevelRankLists = await getAlarmLevelRankList(instance, params)
  alarmLevelRankLists.list = LevelRankLists.data;
  let alarmLevelRank = alarmLevelRankLists.list.concat();

  let getAlarmUnitRanks = await getAlarmUnitRank(instance, params)
  let getAmbulanceAlarmRanks = await getAmbulanceAlarmRank(instance, params)
  let getAmbulanceVennLists = await getAmbulanceVennList(instance, params)
  // let getAlertables = await getAlertable(instance, params)
  let getCurves = await getCurve(instance, params)  // []  0:虚线  1：实线
  let todayCurves = await getTodayCurve(instance, paramsTodayCurve)

  // getCurves的x轴数据
  let X_Curves = []
  getCurves.data.forEach(i => {
    i.forEach(j => {
      X_Curves.push(j.time)
    })
  })
  
  // getAlertables
  for(var key in Venn) {
    Venn[key].value = 0
  }
  let alarmTypeArr = [
    {label: 'WHEELCHAIR_SEATING', value: 'wheelchair'},
    {label: 'SMOKE_DISTRACTION', value: 'smoke'},
    {label: 'PHONE_DISTRACTION', value: 'phone'},
    {label: 'OCCLUSION', value: 'occlusion'},
  ]
  let oldArr = getAmbulanceVennLists?.data?.concat()?.map(i => {
    let obj = alarmTypeArr.find(j => j.label == i.alarmType)
    i['alarmType'] = obj.value
    return i
  });
  let vehicleIDs = [...new Set(getAmbulanceVennLists.data.map(i => i.id))];
  vehicleIDs.forEach(i => {
    let type_str = []
    oldArr.forEach(j => {
      if (i == j.id) type_str.push(j.alarmType)
    })
  
    for(var x in Venn) {
      if (x.split('_').length == type_str.length) {
        let keyStr = x.split('_').sort((a,b) => a.charCodeAt(0) - b.charCodeAt(0)) + ''
        let valStr = type_str.sort((a,b) => a.charCodeAt(0) - b.charCodeAt(0)) + ''
        if (keyStr == valStr) {
          Venn[x].value += 1
        }
      }
    }
  })

  rankList.map((i, ind) => {
    let item = getAlarmUnitRanks.data[ind];
    i.value = item && item.num || 0;
    i.label = item && item.name || '';
    return i;
  });

  // Today’s alarm analysis
  var todayChartDom = today.value;
  var todayChart = echarts.init(todayChartDom);
  let todayOption = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      right: 60,
      bottom: 40
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,     moment().format('HH:MM')
      data: todayCurves.data.map(i => i.time.substr(11) ),
      axisLabel: {  
        interval: 0,
        rotate: 0,
        align: 'center',
        margin: 10
      }
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: function(val) {
        return Object.is(val.max, NaN) ? 80 : val.max
      },
    },
    series: [
      {
        name: 'Today',
        data: todayCurves.data.map(i => i.num ),
        // data: [620, 632, 601, 634, 1190, 1230, 1120],
        type: 'line',
        showSymbol: false,
        smooth: true,
        lineStyle: {
          color:  new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#2CFCFE' },
            { offset: 1, color: '#3A4EFC' }
          ])
        },
        areaStyle: {
          opacity: 0.2,
          color:  new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#2CFCFE' },
            { offset: 1, color: '#3A4EFC' }
          ])
        }
      },
    ]
  };
  todayChart.on('finished', _ => {
    if(todayFirst){
      todayFirst = false;
      todayLoading.value = false; //关闭loading
    }
  })
  todayChart.setOption(todayOption);


  // Comparative analysis of alarms
  var analysisChartDom =  analysis.value;
  var analysisChart = echarts.init(analysisChartDom);
  let analysisOption = {
    tooltip: {
      trigger: 'axis',
      formatter(arr){ 
        let str = ''
        arr.forEach(i => {
          str += i.name + '<br>'+ i.marker + i.seriesName + '：' + i.value + '<br>'
        })
        return str
      },
    },
    legend: {
      show: true,
      data: ['Previous Period', 'Current Period'],
      bottom: 0,
      textStyle: {
        color: '#D3D5D6'
      }
    },
    xAxis: {
      type: 'category',
      data: X_Curves
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: function(val) {
        return Object.is(val.max, NaN) ? 80 : val.max
      },
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      },
    },
    series: [
      {
        name: 'Previous Period',
        data: getCurves.data[0].map(i => {
          return {
            value: i.num,
            name: i.time,
            time: i.time,
          }
        }),
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      {
        name: 'Current Period',
        data: getCurves.data[1].map(i => {
          return {
            value: i.num,
            time: i.time,
            name: i.time
          }
        }),
        type: 'line',
        showSymbol: false,
        smooth: true,
      },
    ]
  };
  analysisChart.on('finished', _ => {
    if(analysisFirst){
      analysisFirst = false
      analysisLoading.value = false //关闭loading
    }
  })
  analysisChart.setOption(analysisOption);

  // Vehicle Alarm Ranking
  var dimensionsChartDom =  dimensions.value;
  var dimensionsChart = echarts.init(dimensionsChartDom);
  let dimensionsOption = {
    xAxis: {
      type: 'category',
      data: getAmbulanceAlarmRanks.data.map(i => i.ambulance),
      axisLabel: {  
        interval: 'auto',
        rotate: 30,
        align: 'center',
        margin: 30
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      top: 40,
      left: 40,
      bottom: 60
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      },
      min: 0,
      max: function(val) {
        return Object.is(val.max, NaN) ? 80 : val.max
      },
    },
    series: [
      {
        data: getAmbulanceAlarmRanks.data.map(i => i.num),
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          borderRadius: [9999, 9999, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2CA5FE' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#3A4EFC' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#3A4EFC' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#2CA5FE' }
            ])
          }
        },
      }
    ]
  };
  dimensionsChart.on('finished', _ => {
    if(dimensionsFirst){
      dimensionsFirst = false;
      dimensionsLoading.value = false; //关闭loading
    };
  });
  dimensionsChart.setOption(dimensionsOption);

  // Alarm level proportion
  var proportionChartDom =  proportion.value;
  var proportionChart = echarts.init(proportionChartDom);
  let proportionOption = {
    color: ['#FB393C', '#F87822', '#F6BB2C', '#B86FDE', '#B86FDE'],
    legend: {
      show: alarmLevelRank.length > 0,
      bottom: '5%',
      left: 'center',
      textStyle: {
        color: '#474C50'
      }
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['40%', '48%'],
        avoidLabelOverlap: false,
        top: 0,
        bottom: 50,
        itemStyle: {
          normal:{
            color: function(val) {
              let _color = type_color.find(i => i.type == val.data.alarmType)?.color
              return _color
            },
            borderRadius: 99999,
            borderColor: '#FFFFFF',
            borderWidth: 4,
          }
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 26,
            formatter(params){ 
              return `${params.percent}%`
            },
            fontWeight: 'bold'
          },
        },
        labelLine: {
          show: false
        },
        // data: []
        data: alarmLevelRank.map(i => {
          let obj = selectAlgorithm.value.find(j => j.value == i.alarmType)
          i['name'] = obj?.label || '';
          i['value'] = i.num;
          console.log(i, '===================================');
          return i;
        })
      }
    ]
  };
  proportionChart.on('finished', _ => {
    if(proportionFirst){
      proportionFirst = false;
      proportionLoading.value = false; //关闭loading
    };
  });
  proportionChart.setOption(proportionOption);

  
  // Ranking of alarms for stationed units
  let maxRank = rankList[0].value;
  rankList.value = rankList.map(i => {
    i['progress'] = i.value ? ((i.value / maxRank) * 100).toFixed(2) : 0;
    return i;
  })
  
  window.addEventListener("resize",function (){
    todayChart.resize();
    analysisChart.resize();
    dimensionsChart.resize();
    proportionChart.resize();
  })
}


let updataEchart = async () => {
  let time = new Date();  
  let params = {
    type: searchForm.type,
    ambulanceId: searchForm.ambulanceId,
    alarmType: searchForm.alarmType,
    startTime: searchForm.date && searchForm.date[0] + ' 00:00:00' || moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: searchForm.date && searchForm.date[1] + ' 23:59:59' || moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  let getCurves = await getCurve(instance, params)  // []  0:虚线  1：实线
  
  // Comparative analysis of alarms
  var analysisChartDom =  analysis.value;
  var analysisChart = echarts.init(analysisChartDom);
  analysisLoading.value = true // 打开loading
  let analysisOption = {
    tooltip: {
      trigger: 'axis',
      formatter(arr){ 
        let str = ''
        arr.forEach(i => {
          str += i.name + '<br>'+ i.marker + i.seriesName + '：' + i.value + '<br>'
        })
        return str
      },
    },
    legend: {
      show: true,
      data: ['Previous Period', 'Current Period'],
      bottom: 0,
      textStyle: {
        color: '#D3D5D6'
      }
    },
    xAxis: {
      type: 'category',
      data: getCurves.data[1].map(i => i.time)
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: 'Previous Period',
        data: getCurves.data[0].map(i => {
          return {
            value: i.num,
            name: i.time,
            time: i.time,
          }
        }),
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      {
        name: 'Current Period',
        data: getCurves.data[1].map(i => {
          return {
            value: i.num,
            time: i.time,
            name: i.time
          }
        }),
        type: 'line',
        showSymbol: false,
        smooth: true,
      },
    ]
  };
  analysisChart.on('finished', _ => {
    analysisLoading.value = false //关闭loading
  })
  analysisChart.setOption(analysisOption);
}


</script>
<template>
  <div class="alarm_index">
    <SearchTable class="search_box" :searchForm="searchForm" :selectClassification="selectClassification" @onSearch="onSearch" />
    <div class="total_row marBottom20 h360">
      <div class="total_item">
        <!-- <div class="title_item row_drop">Ranking of alarms for stationed units</div> -->
        <div class="title_item row_drop">City Alarm Ranking</div>
        <div class="rank_list">
          <div class="rank_item" v-for="(item, index) in rankList" :key="index">
            <img :src="item.imgSrc" alt="">
            <div class="rank_content">
              <div class="rank_title">{{ item.label }}</div>
              <div class="rank_progress" :style="{width: (item.progress ? item.progress : 0) + '%'}"></div>
            </div>
            <div class="rank_val">{{ item.value }}</div>
          </div>
        </div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Alarm Proportion</div>
        <div ref="proportion" v-loading="proportionLoading" class="echarts_box" :style="{opacity: alarmLevelRankLists.list.length ? 1 : 0}" ></div>
        <div class="no_data_css_Proportion"  v-show="!alarmLevelRankLists.list.length">No Data</div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Vehicle Venn Diagram</div>
        <VennChart :Venn="Venn"></VennChart>
        <!-- <VennCharts :Venn="Venn"></VennCharts> -->
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Vehicle Alarm Ranking</div>
        <div ref="dimensions" v-loading="dimensionsLoading" class="echarts_box"></div>
      </div>
    </div>
    <div class="total_row h484">
      <div class="total_item  form_search_echarts">
        <div class="alarms_title">
          <div class="title_item row_drop">Comparative Alarms Analysis</div>
          <el-select
            v-model="searchForm.alarmType"
            placeholder="Please Select"
            @change="updataEchart"
            clearable
          >
            <el-option v-for="item in algorithmSelect" :key="item.label" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div ref="analysis" v-loading="analysisLoading" class="echarts_box"></div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Today’s Alarm Analysis</div>
        <div ref="today" v-loading="todayLoading" class="echarts_box"></div>
      </div>
    </div>  
  </div>
</template>
<style scoped lang="less">
.alarm_index{
  color: var(--mw-font-color-content);
  height: calc(100vh - 110px);
  background-color: var(--mw-page-background-color);
  padding: 20px;
  // height: 100%;
  display: flex;
  flex-direction: column;
  .total_row{
    display: flex;
    justify-content: space-between;
    .total_item{
      flex: 1;
      height: 100%;
      padding: 20px;
      margin-right: 20px;
      box-shadow: 0px 6px 12px 1px rgba(26,84,193,0.1);
      border-radius: 8px;
      background-color: var(--mw-page-background-bright-color);
      position: relative;
      .alarms_title{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
      }
      .echarts_box{
        width: 100%;
        height: calc(100% - 24px);
      }
      .Ven_pic{
        width: 296px;
        height: calc(100% - 24px);  // 296px
        position: relative;
        margin: 0 auto;
        .Ven_value{
          position: absolute;
          transform: translate(-50%, -50%);
          user-select: none;
        }
        .Ven_value_phone{
          left: 24%;
          top: 30%;
        }
        .Ven_value_phone_smoke{
          left: 50%; 
          top: 25%;
        }
        .Ven_value_smoke{
          right: 20%;
          top: 30%;
        }
        .Ven_value_phone_wheelchair{
          left: 34%;
          top: 53%;
        }
        .Ven_value_phone_smoke_wheelchair{
          left: 50%;
          top: 44%;
        }
        .Ven_value_smoke_wheelchair{
          right: 28%;
          top: 53%;
        }
        .Ven_value_wheelchair{
          left: 50%;
          bottom: 22%;
        }
        .Ven_pic_round{
          position: absolute;
          transform: translate(-50%, -50%);
          width: 160px;
          height: 160px;
          border-radius: 99999px;
        }
        
        .txt_Phone{
          color: #FB393C;
          background-color: transparent;
        }
        .txt_Smoke{
          color: #F8780B;
          background-color: transparent;
        }
        .txt_Wheelchair{
          color: #E0AA26;
          background-color: transparent;
        }
        .Ven_pic_phone{
          top: 108px;
          left: calc(50% - 40px);
          background-color: rgba(230, 11, 24, 0.2);
          span{
            position: absolute;
            left: -20px;
            top: 4px;
          }
        }
        .Ven_pic_smoke{
          top: 108px;
          left: calc(50% + 40px);
          background-color: rgba(248, 120, 11, 0.2);
          span{
            position: absolute;
            right: -22px;
            top: 4px;
          }
        }
        .Ven_pic_wheelchair{
          bottom: -40px;
          left: 50%;
          background-color: rgba(224, 170, 38, 0.2);
          span{
            position: absolute;
            left: 50%;
            bottom: -30px;
            transform: translate(-50%, -50%);
          }
        }
      }
      .rank_list{
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        height: calc(100% - 24px);
        .rank_item{
          display: flex;
          align-items: center;
          justify-content: space-between;
          img{
            width: 30px;
            height: 30px;
          }
          .rank_content{
            flex: 1;
            margin: 0 10px;
            .rank_title{
              font-size: 14px;
            }
            .rank_progress{
              height: 6px;
              margin: 4px 0;
              border-radius: 1px;
              background: linear-gradient(90deg, #3a8cfc, #3a4efc);
            }
          }
          .rank_val{
            width: 30px;
            text-align: center;
          }
        }
        .rank_item:nth-child(-n+3){
          .rank_content{
            .rank_progress{
              background: linear-gradient(90deg, #FB393C, #FB396D);
            }
          }
        }
        
      }
      .title_item{
        color: var(--mw-font-color-title);
        font-size: 16px;
        line-height: 24px;
      }
    }
    .total_item:nth-last-child(1){
      margin-right: 0;
    }
  }
  .h360{min-height: 360px; height: 360px;}
  .h484{
    min-height: 300px;
    flex: 1;
  }
  .marBottom20{margin-bottom: 20px;}
  .no_data_css_Proportion{
    position: absolute;
    left: 50%;
    top: 70px;
    transform: translate(-50%, -50%);
    font-size: 20px;
    text-align: center;
    margin-top: 120px;
  }
  .no_data_css{
    font-size: 20px;
    text-align: center;
    margin-top: 120px;
  }
}
</style>